﻿using System;
using Cesave.Presentation.Permisos.WinForms.Client.ViewModelBase;
using Cesave.Presentation.Permisos.WinForms.Client.Views.Access;
using System.Globalization;
using Cesave.Presentation.Permisos.WinForms.Client.Resources;
using System.Windows.Forms;
using Cesave.Application.Permisos.Settings;
using Cesave.Infrastructure.CrossCutting.IoC;
using System.ComponentModel;
using System.ServiceModel.Security;
using System.ServiceModel;
using Cesave.Application.Permisos.ServiceAgent;

namespace Cesave.Presentation.Permisos.WinForms.Client.ViewModels.Access
{
    public partial class LoginViewModel
        : ObservableObject
    {
        #region Private properties

        private delegate void ShowMessageDelegate(Control owner, string message, string caption, MessageBoxButtons buttons, MessageBoxIcon icon);
        private string _username;
        private string _password;
        private PermisosModuleServiceWrapper _serviceClient;
        private LoginView _view;
        private IPUSSettings _pusSettings;

        #endregion

        #region Constructor

        public LoginViewModel(LoginView view)
        {
            if (view == (LoginView)null)
                throw new ArgumentNullException("view");
            _pusSettings = IoCFactory.Resolve<IPUSSettings>();
            _view = view;
            WireUpEvents();
        }

        #endregion

        #region Event methods

        /// <summary>
        /// Suscribe los elementos de la vista a sus
        /// eventos correspondientes
        /// </summary>
        private void WireUpEvents()
        {
            PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(LoginViewModel_PropertyChanged);
            _view.Load += LoadView;
            _view.loginButton.Click += Login;
            _view.exitButton.Click += Exit;
        }

        private void Login(object sender, EventArgs e)
        {
            if (_view.loginValidator.Validate().IsValid)
            {
                _username = _view.usernameTextEditor.Text;
                _password = _view.passwordTextEditor.Text;
                using (BackgroundWorker worker = new BackgroundWorker())
                {
                    _view.loginButton.Enabled = false;
                    _view.exitButton.Enabled = false;
                    worker.DoWork += delegate(object wSender, DoWorkEventArgs wEvent)
                    {
                        try
                        {
                            _serviceClient = new PermisosModuleServiceWrapper(_username, _password);
                            _pusSettings.Password = _password;
                            _pusSettings.Agente = _serviceClient.FindAgenteByUsuario(_username);
                            _pusSettings.Junta = _serviceClient.FindJuntaByGuid(_pusSettings.Agente.JuntaGuid);
                        }
                        catch (MessageSecurityException ex)
                        {
                            wEvent.Result = ex;
                        }
                        catch (EndpointNotFoundException ex)
                        {
                            wEvent.Result = ex;
                        }
                    };
                    worker.RunWorkerCompleted += delegate(object wSender, RunWorkerCompletedEventArgs wEvent)
                    {
                        _view.exitButton.Enabled = true;
                        _view.loginButton.Enabled = true;
                        if (wEvent.Result is Exception)
                        {
                            string message = string.Empty;
                            if (wEvent.Result is MessageSecurityException)
                                message = "Verifique sus credenciales.";
                            else if (wEvent.Result is EndpointNotFoundException)
                                message = string.Format("No se encontró el servicio en la dirección {0}", _serviceClient.Endpoint.Address.Uri.AbsoluteUri);
                            MessageBox.Show(_view, message, WindowTitles.LoginWindowTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                            _view.Close();
                    };
                    worker.WorkerSupportsCancellation = true;
                    worker.RunWorkerAsync();
                }
            }
        }

        private void Exit(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void LoadView(object sender, EventArgs e)
        {
            _view.Text = string.Format(
                CultureInfo.InvariantCulture,
                WindowTitles.LoginWindowTitle
            );
        }

        #endregion

    }
}
